<?php
/**
 * 功能: 积分商品兑换
 * User: 文丹
 * Date: 2018/7/26 0026
 * Time: 11:11
 */

namespace app\index\controller;
use think\Controller;
use think\Db;

class Convert extends Controller{
    /**
     * 积分商品展示
     */
    public function index(){
        $goods = Db::name('product')->where('is_down',2)->select();
        if($goods){
            return json(['msg'=>'请求成功！','ok'=>true,'goods'=>$goods]);
        }else{
            return json(['msg'=>'暂无数据！','ok'=>false]);
        }

    }
    /**
     * 积分商品兑换
     */
    public function change(){
        $token = trim(input('token'));
        if(empty($token)){
            return json(['msg'=>'token不能为空！','ok'=>false]);
        }
        $user_id = getUserId($token);
        $product_id = intval(input('id'));
        $integral = intval(input('integral'));
        $data = [
            'user_id'=>$user_id,
            'product_id'=>$product_id,
            'integral'=>$integral,
            'time'=>time()
        ];

        // 启动事务
        Db::startTrans();
        try {
            //修改用户总积分数量
            $y = Db::table('user')->where('id',$user_id)->value('integral');
            $n = $y - $integral;
            if($n<0){
                return json(['msg'=>'积分不足不能兑换！','ok'=>false]);
            }
            Db::table('user')->where('id',$user_id)->update(['integral'=>$n]);

            //积分变动记录
            $title = Db::table('product')->where('id',$product_id)->value('title');
            $data1 = [
                'user_id'=>$user_id,
                'integral'=>$integral,
                'remark'=>'积分兑换商品《'.$title."》",
                'state'=>2,//1收入，2支出
                'time'=>time()
            ];
            Db::name('integral_record')->insert($data1);

            //兑换历史添加
            Db::table('history')->insert($data);
            // 提交事务
            Db::commit();
            return json(['msg'=>'兑换成功','ok'=>true]);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return json(['msg'=>'兑换失败，请稍后再试','ok'=>false]);
        }
    }
    /**
     * 兑换历史
     */
    public function history(){
        $token = trim(input('token'));
        if(empty($token)){
            return json(['msg'=>'token不能为空！','ok'=>false]);
        }
        $user_id = getUserId($token);
        $history = Db::name('history')->where('user_id',$user_id)->select();

        $arr = [];
        if($history){
            foreach($history as $k=>$v){
                $arr[$k] = $v;
                $product = Db::name('product')->where('id',$v['product_id'])->find();
                $arr[$k]['title'] = $product['title'];
                $arr[$k]['intro'] = $product['intro'];
                $arr[$k]['img'] = array_filter(explode(',',$product['image']));

            }
        }

        if($arr){
            return json(['msg'=>'请求成功','ok'=>true,'history'=>$arr]);
        }else{
            return json(['msg'=>'暂无兑换历史！','ok'=>false]);
        }

    }

}